#!/bin/bash

# Staging环境部署脚本
# 将Staging配置部署到服务器

SERVER_IP="47.237.10.129"
SERVER_USER="root"
STAGING_PORT="3001"

echo "🚀 部署Staging环境到服务器..."
echo "服务器: $SERVER_IP"
echo "========================================"

# 1. 上传配置文件
echo "📤 上传配置文件..."
scp backend/.env.staging $SERVER_USER@$SERVER_IP:/opt/cumbull/backend/
scp nginx-staging.conf $SERVER_USER@$SERVER_IP:/etc/nginx/conf.d/staging.conf
scp scripts/staging/*.* $SERVER_USER@$SERVER_IP:/opt/cumbull/scripts/staging/

# 2. 在服务器上执行部署
echo "🔧 在服务器上执行部署..."
ssh $SERVER_USER@$SERVER_IP << 'REMOTE_EOF'
echo "🔧 开始服务器端部署..."

# 进入项目目录
cd /opt/cumbull/backend

# 创建必要目录
mkdir -p logs uploads/staging scripts/staging

# 停止现有Staging进程
echo "停止现有Staging服务..."
pm2 delete cumrbull-staging 2>/dev/null || echo "没有运行的Staging进程"
sleep 2

# 安装依赖（如果需要）
if [ ! -d "node_modules" ]; then
    echo "安装Node.js依赖..."
    npm install --production
fi

# 启动Staging服务
echo "启动Staging服务..."
if [ -f "production-server.js" ]; then
    NODE_ENV=staging pm2 start production-server.js --name "cumrbull-staging" --env staging
elif [ -f "start-server.js" ]; then
    NODE_ENV=staging pm2 start start-server.js --name "cumrbull-staging" --env staging
else
    echo "❌ 找不到启动文件"
    exit 1
fi

# 保存PM2配置
pm2 save

echo "等待服务启动..."
sleep 5

# 测试Nginx配置
echo "测试Nginx配置..."
nginx -t
if [ $? -eq 0 ]; then
    echo "✅ Nginx配置语法正确"
    systemctl reload nginx
    echo "✅ Nginx已重新加载"
else
    echo "❌ Nginx配置语法错误"
    exit 1
fi

# 检查服务状态
echo "\n📊 检查服务状态..."
echo "PM2进程状态:"
pm2 status

echo "\n端口监听状态:"
netstat -tlnp | grep -E ':(80|443|3000|3001)'

echo "\n测试Staging健康检查:"
curl -s http://localhost:3001/health || echo "Staging健康检查失败"

echo "\n✅ Staging环境部署完成"
REMOTE_EOF

# 3. 验证部署结果
echo "\n🧪 验证部署结果..."
echo "测试Staging API健康检查:"
if curl -s -m 10 https://staging-api.cumrbull.com.sg/health; then
    echo "✅ Staging API健康检查正常"
else
    echo "⚠️ Staging API健康检查失败（可能需要配置DNS和SSL）"
fi

echo "\n🎉 Staging环境部署完成！"
echo "========================================"
echo "📋 后续步骤:"
echo "1. 配置DNS解析: staging-api.cumrbull.com.sg -> $SERVER_IP"
echo "2. 配置DNS解析: staging-admin.cumrbull.com.sg -> $SERVER_IP"
echo "3. 申请SSL证书: certbot certonly --nginx -d staging-api.cumrbull.com.sg -d staging-admin.cumrbull.com.sg"
echo "4. 创建Staging数据库: mysql < scripts/staging/create-staging-database.sql"
echo "5. 测试数据库连接: node scripts/staging/test-staging-database.js"
echo "6. 运行数据迁移: node scripts/staging/migrate-to-staging.js"
echo "7. 验证Staging环境: ./connectivity-test.sh"
